<?php
include('./fun.php');include('./hd_fun.php');
$conn=my_sql($cfg);
$re=user_login();
if($re['err']=='no_login'){direct('login.php?t='.time());exit;}
if($re['err']!='ok'){die($re['err']);}
$user=$re['user'];
$shop_id=$re['shop_id'];
$shop=get_shop();
$set=get_set();
$id=g('id');
if(!$id and !is_numeric($id)){die('请选择商品');}
$sql='select * from '.$cfg['e'].'pro where id="'.a($id).'" and shop_id="'.$shop['id'].'" ';



$l=db1($sql);
if(!$l){die('没有找到商品，或您的没有编辑的权限');}

if($l['data']){
    $l['data']=unserialize(out($l['data']));
    $specs = $l['data'];
}else{
    $specs = [];
}

$sql='select c from '.$cfg['e'].'pro where shop_id="'.$shop['id'].'" ';
$cc=db($sql);
if($cc){
foreach($cc as $v){
    if($v['c']){
$c[$v['c']]=$v['c'];
}
}
}



?>
<style>
pro_box{float:left;width:100%;height:100%;}
bottom_index{position:absolute;width:100%;left:0;bottom:0;z-index:100;padding-left:10px}
/* 添加新样式 */
.spec-item {
    border: 1px solid #ddd;
    padding: 10px;
    margin: 5px 0;
    border-radius: 4px;
    position: relative;
    height: 58px;
}
.spec-item input {
    width: 22% !important;
    margin: 0 1% !important;
}
.spec-delete {
    position: absolute;
    right: 10px;
    top: 10px;
    color: red;
    cursor: pointer;
}
.add-spec-btn {
    background: #28a745;
    color: white;
    padding: 5px 15px;
    border-radius: 4px;
    cursor: pointer;
    display: inline-block;
    margin: 10px 0;
}
</style>

<pro_box>
<l><text>名称</text>
<input placeholder="商品的名称" value="<?php echo base64($l['title'])?>" c="title" need="1" onchange="val_change($(this))">
</l>

<l style="height:auto" id="c"><text>分类</text>
<input placeholder="商品分类" value="<?php echo $l['c']?>" c="c" need="1" onchange="val_change($(this))">
<?php if($c){echo '<index  style="margin-top:5px">';foreach($c as $v){echo '<a onclick="select_this_c($(this))" class="m '.($l['c']==$v?'select':'').'">'.$v.'</a>';}echo '</index>';}?>

</l>

<l><text>售价</text>
<input placeholder="商品的价格" value="<?php echo $l['price']?>" c="price" need="1" onchange="val_change($(this))" type="number">
</l>

<l><text>原价</text>
<input placeholder="划线价格" value="<?php echo $l['old']?>" c="old"  onchange="val_change($(this))" type="number">
</l>

<l><text>库存</text>
<input placeholder="<?php echo ($l['total']==-1?'无限数量':($l['total']>0?$l['total']:'库存不足'))?>" value="<?php echo ($l['total']<=0?'':$l['total'])?>" c="total"  onchange="val_change($(this))" type="number">
</l>
<!-- 添加规格管理部分 -->
<l id="spec_box">
    <text>商品规格</text>
    <div class="add-spec-btn" onclick="addSpec()">添加规格</div>
    <div id="specs_container">
        <?php
        // 解析已存在的规格数据（假设存储为JSON字符串）
        if($l['data']){
        foreach ($l['data'] as $index => $spec):
            ?>
            <div class="spec-item">
                <span class="spec-delete" onclick="deleteSpec(this)">×</span>
                <input placeholder="规格标题" value="<?= $spec['title'] ?>" c="specs[<?= $index ?>][c]">
                <input placeholder="价格" value="<?= $spec['price'] ?>" type="number" c="specs[<?= $index ?>][price]">
                <input placeholder="<?php echo ($spec['num']==-1?'无限数量':($spec['num']>0?$spec['num']:'库存不足'))?>" value="<?= $spec['num']<= 0?'':$specs['num'] ?>" type="number" c="specs[<?= $index ?>][num]">
                <input placeholder="限购" value="<?= $spec['xiangou'] ?>" type="number" c="specs[<?= $index ?>][xiangou]">
            </div>
        <?php endforeach;} ?>
    </div>
</l>


<l><text>计量单位</text>
<input placeholder="计量单位" value="<?php echo $l['daiwei']?>" c="daiwei"  onchange="val_change($(this))" >
</l>

<l id="x"><text>特色</text>
<input id="is_new"  value="<?php echo $l['is_new']?>" c="is_new"  type="hidden">
<input id="is_hot"  value="<?php echo $l['is_hot']?>" c="is_hot"  type="hidden">
<index>
<?php echo '<a class="m '.($l['is_new']==1?'select':'').'" onclick="select_x($(this))" c="is_new">新品</a>';?>
<?php echo '<a class="m '.($l['is_hot']==1?'select':'').'" onclick="select_x($(this))" c="is_hot">热销</a>';?>
</index>
</l>

<l><text>商品说明</text>
<input placeholder="商品特色简要说明" value="<?php echo json_decode($l['info'])?>" c="info"  onchange="val_change($(this))" >
</l>

</pro_box>


<bottom_index>
<index><a class="m b" onclick="submit($(this))">提交修改</a></index>
</bottom_index>









<script>


    // 保持原有函数不变，添加新功能
    let specIndex = <?= count($specs) ?>; // 初始化规格计数器

    function addSpec() {
        console.log(specIndex);
        const html = `
    <div class="spec-item">
        <span class="spec-delete" onclick="deleteSpec(this)">×</span>
        <input placeholder="规格标题" c="specs[${specIndex}][c]">
        <input placeholder="价格" type="number" c="specs[${specIndex}][price]">
        <input placeholder="数量" type="number" c="specs[${specIndex}][num]">
        <input placeholder="限购" type="number" c="specs[${specIndex}][xiangou]">
    </div>`;

        $('#specs_container').append(html);
        specIndex++;
    }

    function deleteSpec(el) {
        $(el).parent().remove();
    }
function submit(){
var re=form_data($('pro_box input'));
if(re.can){return;}
var data=re.data;

   data['data'] =  transformSpecs(data)

post('pro_change',data,'<?php echo $l['id']?>',function(res){
    msg('保存成功');
    main_load();
});
}

function select_this_c(o){
var val=o.html();
$('#c input').val(val);
$('#c index a').removeClass('select');
o.addClass('select');

}

function select_x(o){
var c=o.attr('c');
var x=o.hasClass('select');var val=1;
if(x){val=0;}
$('#'+c).val(val);
if(val==1){o.addClass('select');}else{o.removeClass('select');}
}
    function transformSpecs(input) {
        const resultMap = {};

        // 遍历对象属性
        for (const key in input) {
            if (!key.startsWith('specs[')) continue;

            // 解析键名格式：specs[id][field]
            const match = key.match(/specs\[(\d+)\]\[(\w+)\]/);
            if (!match) continue;

            const id = match[1];
            const field = match[2];
            const value = input[key];

            // 初始化规格对象
            if (!resultMap[id]) {
                resultMap[id] = { id: parseInt(id) };
            }

            // 特殊处理 num 字段
            if (field === 'num') {
                resultMap[id][field] = value === "" ? -1 : parseInt(value) || -1;
            } else {
                resultMap[id][field] = value;
            }
        }
        // 创建一个新对象，键为规格ID，值为规格对象
        const output = {};
        for (const id in resultMap) {
            output[id] = {
                c: resultMap[id].c,
                price: resultMap[id].price,
                num: resultMap[id].num,
                xiangou: resultMap[id].xiangou
            };
        }

        return output;

        // 转换为数组并按 id 升序排序
        // return Object.values(resultMap)
        //     .sort((a, b) => a.id - b.id)
        //     .map(({ c, price, num, xiangou }) => ({
        //         c: c || "",
        //         price: price || "",
        //         num: num !== undefined ? num : -1,
        //         xiangou: xiangou || ""
        //     }));
    }
    function convertToSpecArray(input) {
        const specs = [];
        const regex = /^specs\[(\d+)\]\[([a-z]+)\]$/;

        for (const key in input) {
            const match = key.match(regex);
            if (!match) continue;

            const [, index, field] = match;
            const numericIndex = parseInt(index, 10);
            const value = input[key];
            console.log("value", value);

            if (!specs[numericIndex]) {
                specs[numericIndex] = {
                    c: '',
                    price: '',
                    num: '',
                    xiangou: ''
                };
            }

            // 新增 num 字段特殊处理逻辑
            if (field === 'num') {
                const num = parseInt(value, 10);
                specs[numericIndex][field] = isNaN(num) ? -1 : num; // 转换失败时设为 -1
            } else {
                specs[numericIndex][field] = value; // 其他字段保持原值
            }
        }

        return specs;
    }
</script>